package logic

import (
	"errors"
	"go_wep_demo/dao/mysql"
	"go_wep_demo/models"
	"go_wep_demo/pkg/jwt"
	"go_wep_demo/pkg/snowflake"
)

// SignUp 用户注册
func SignUp(data *models.ParamSignUp) (err error) {
	err = mysql.CheckUserNameIsIsSet(data.Username)
	if err != nil {
		return err
	}
	userId := snowflake.GenId()
	//构造一个用户实例
	user := &models.User{
		UserId:   userId,
		Username: data.Username,
		Password: data.Password,
		Email:    data.Email,
	}
	err = mysql.InsertUser(user)
	if err != nil {
		return err
	}
	return nil
}

// Login 用户登录
func Login(data *models.ParamLogin) (loginStruct models.LoginStruct, err error) {
	var user = models.User{}
	user, err = mysql.FindUserByUsername(data.Username)
	if err != nil {
		return loginStruct, err
	}
	pwd := mysql.EncodePwd(data.Password)
	if user.Password != pwd {
		return loginStruct, errors.New("密码错误")
	}
	//userInfo = models.UserInfo{
	//	Username: user.Username,
	//	UserId:   user.UserId,
	//	Email:    user.Email,
	//	Gender:   common.GetUserGender(user.Gender),
	//}
	var aToken string
	var rToken string
	aToken, rToken, err = jwt.GenToken(user.UserId)
	if err != nil {
		return loginStruct, errors.New("生成token失败")
	}
	loginStruct = models.LoginStruct{
		Token:        aToken,
		RefreshToken: rToken,
	}
	return loginStruct, nil
}
